<?php
/**
 * +--------------------------------------------------------+
 * @Created by Phpstorm.
 * @Category test_swoole.php
 * @Depiction
 * @Author hwy
 * @Date 2021/4/15  14:03
 * +--------------------------------------------------------+
 */

use App\Services\HttpServer;

include '../vendor/autoload.php';
//创建线程 - 多线程爬虫方法
// chanMore();

//mysql连接池
connectionPool();

/**
 * +----------------------------------------------------------+
 * 创建线程 - 多线程爬虫方法
 * +----------------------------------------------------------+
 */
function chanMore()
{
    $t1 = microtime(true);
    // for ($i = 0; $i < 3; $i++) {
    //     $content = get_info($i);
    // }
    for ($i = 0; $i < 3; $i++) {
        $pro = new \swoole_process(function (\swoole_process $work) use ($i) {
            //方法
            echo 'get_info for ' . $i . PHP_EOL;
            sleep(20);
            $content = true;
            //写入管道
            $work->write($content . PHP_EOL);

        }, true);

        $pro_id          = $pro->start();
        $worker[$pro_id] = $pro;
    }

    foreach ($worker as $v) {
        echo $v->read() . PHP_EOL;
    }

    //进程回收
    \swoole_process::wait();

    $t2 = microtime(true);
    $t3 = (($t2 - $t1) * 1000) . 'ms';
    echo $t3 . PHP_EOL;
}

/**
 * +----------------------------------------------------------+
 * mysql连接池
 * +----------------------------------------------------------+
 */
function connectionPool()
{
    $server = new HttpServer('0.0.0.0', 5200);
    $server->start();

    dd(1234);


    go(function () {
        // All MySQL connections: [10, 30]
        $pool = new \Smf\ConnectionPool\ConnectionPool(
            [
                'minActive'         => 10,
                'maxActive'         => 30,
                'maxWaitTime'       => 5,
                'maxIdleTime'       => 20,
                'idleCheckInterval' => 10,
            ],
            new \Smf\ConnectionPool\Connectors\CoroutineMySQLConnector(),
            [
                'host'        => '127.0.0.1',
                'port'        => '3306',
                'user'        => 'root',
                'password'    => 'root',
                'database'    => 'laravel_admin',
                'timeout'     => 3,
                'charset'     => 'utf8mb4',
                'strict_type' => true,
                'fetch_mode'  => true,
            ]
        );
        echo "Initializing connection pool\n";
        $pool->init();
        defer(function () use ($pool) {
            echo "Closing connection pool\n";
            $pool->close();
        });

        echo "Borrowing the connection from pool\n";
        /**@var MySQL $connection */
        $connection = $pool->borrow();

        $status = $connection->query('select COUNT(*) from la_test');

        echo "Return the connection to pool as soon as possible\n";
        $pool->return($connection);

        var_dump($status);
    });

}


